// com/example/teacherservice/service/TeacherCourseService.java
package com.example.teacherservice.service;

import com.example.teacherservice.dto.*;
import com.example.teacherservice.entity.*;
import com.example.teacherservice.entity.Class;
import com.example.teacherservice.exception.ResourceNotFoundException;
import com.example.teacherservice.repository.*;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.time.ZoneId;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class TeacherCourseService {

    private final CourseRepository courseRepository;
    private final ChapterRepository chapterRepository;
    private final StuCourseRepository stuCourseRepository;
    private final CouClassRepository couClassRepository;
    private final StuCourseAppraiseRepository commentRepository;
    private final StudentRepository studentRepository;
    private final ClassRepository classRepository;

    /**
     * 获取课程详情（教师视角）
     */
    public TeacherCourseDetailDTO getCourseDetail(Long courseId) {
        // 1. 查询课程基本信息
        Course course = courseRepository.findById(courseId)
                .orElseThrow(() -> new ResourceNotFoundException("课程不存在"));

        // 2. 查询章节详情
        List<Chapter> chapters = chapterRepository.findByCourseIdAndDeleted(courseId, 0);
        List<ChapterDetailDTO> chapterDetails = chapters.stream()
                .map(ch -> ChapterDetailDTO.builder()
                        .id(ch.getId())
                        .courseId(ch.getCourseId())
                        .index(ch.getIndex())
                        .title(ch.getTitle())
                        .url(ch.getUrl())
                        .sortOrder(ch.getSortOrder())
                        .createTime(ch.getCreateTime())
                        .updateTime(ch.getUpdateTime())
                        .build())
                .collect(Collectors.toList());

        // 3. 查询选课学生
        List<StuCourse> stuCourses = stuCourseRepository.findByCourseId(courseId);
        List<StudentInfoDTO> students = stuCourses.stream()
                .map(sc -> {
                    Student student = studentRepository.findById(sc.getStuId())
                            .orElseThrow(() -> new ResourceNotFoundException("学生不存在"));
                    return StudentInfoDTO.builder()
                            .stuId(student.getId())
                            .stuName(student.getName())
                            .joinTime(sc.getCreateTime())
                            .build();
                })
                .collect(Collectors.toList());

        // 4. 查询关联班级
        List<CouClass> couClasses = couClassRepository.findByCourseId(courseId);
        List<ClassInfoDTO> classes = couClasses.stream()
                .map(cc -> {
                    Class classEntity = classRepository.findById(cc.getClassId())
                            .orElseThrow(() -> new ResourceNotFoundException("班级不存在"));


                    ClassInfoDTO dto = new ClassInfoDTO();
                    dto.setId(classEntity.getId());
                    dto.setClassName(classEntity.getClassName());

                    return dto;
                })
                .collect(Collectors.toList());

        // 5. 查询课程评论
        List<StuCourseAppraise> comments = commentRepository.findByCourseId(courseId);
        List<CommentDetailDTO> commentDetails = comments.stream()
                .map(c -> {
                    Student student = studentRepository.findById(c.getStudentId()).orElse(null);
                    CommentDetailDTO.CommentDetailDTOBuilder builder = CommentDetailDTO.builder()
                            .id(c.getId())
                            .content(c.getContent())
                            .score(c.getScore())
                            .createTime(c.getCreateTime());

                    if (student != null) {
                        builder.studentId(student.getId())
                                .studentName(student.getName());
                    } else {
                        // 学生不存在时的友好处理
                        builder.studentId(null)
                                .studentName("匿名用户");
                    }

                    return builder.build();
                })
                .collect(Collectors.toList());

        // 6. 组装DTO
        return TeacherCourseDetailDTO.builder()
                .id(course.getId())
                .teaId(course.getTeaId())
                .couName(course.getCouName())
                .couIntroduction(course.getCouIntroduction())
                .couPic(course.getCouPic())
                .couTypeId(course.getCouTypeId())
                .couParTypeId(course.getCouParTypeId())
                .couPrice(course.getCouPrice())
                .couCataNum(course.getCouCataNum())
                .couCollNum(course.getCouCollNum())
                .couLikeNum(course.getCouLikeNum())
                .couShareNum(course.getCouShareNum())
                .clicks(course.getClicks())
                .purchase(course.getPurchase())
                .chapters(chapterDetails)
                .students(students)
                .classes(classes)
                .comments(commentDetails)
                .build();
    }


    @Transactional
    public void addStudentToCourse(Long courseId, Long studentId) {
        // 检查是否已经存在关联
        if (stuCourseRepository.existsByStuIdAndCourseId(studentId, courseId)) {
            throw new RuntimeException("该学生已经加入本课程");
        }

        // 创建新的关联
        StuCourse stuCourse = new StuCourse();
        stuCourse.setStuId(studentId);
        stuCourse.setCourseId(courseId);

        stuCourseRepository.save(stuCourse);
    }

    @Transactional
    public void removeStudentFromCourse(Long courseId, Long studentId) {
        // 检查关联是否存在
        if (!stuCourseRepository.existsByStuIdAndCourseId(studentId, courseId)) {
            throw new RuntimeException("该学生未加入本课程");
        }

        // 删除关联
        stuCourseRepository.deleteByStuIdAndCourseId(studentId, courseId);
    }
}